package com.cfweb.util;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.node.Node;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static org.elasticsearch.node.NodeBuilder.*;

@Component
public class ConnectES implements InitializingBean{
	@Value("#{configProperties['clustername']}")
	private String clusterName;
	@Value("#{configProperties['clientModel']}")
	private String clientModel;
	@Value("#{configProperties['host1']}")
	private String host1;
	@Value("#{configProperties['host2']}")
	private String host2;
	@Value("#{configProperties['host3']}")
	private String host3;
	@Value("#{configProperties['port']}")
	private int port;
	
	Settings settings;
	private Client client =null;
    @Override
	public void afterPropertiesSet() throws Exception {
            settings = ImmutableSettings.settingsBuilder().put("cluster.name", clusterName).build();
            System.out.println(clusterName);
            if(client==null){
                if(clientModel.equals("NODE")){
                    Node node = nodeBuilder().clusterName(clusterName).client(true).node();
                    client = node.client();
                }
                else if(clientModel.equals("TRANSPORT")){
                    System.out.println("TRANSPORT");
                    settings = ImmutableSettings.settingsBuilder().put("cluster.name", "CFLog").build(); 
                    client= new TransportClient(settings)
                        .addTransportAddress(new InetSocketTransportAddress(host1,port))
                        .addTransportAddress(new InetSocketTransportAddress(host2,port))
                        .addTransportAddress(new InetSocketTransportAddress(host3,port));
                }
                else {
                    System.out.println("clientModel is not correct.");
                }
            }
    }
	public Client getClient(){
		return this.client;
	}
}
